/*
 * Simulator
 *
 * SJSU CS 149 Spring 2009 Project
 *
 * Copyright 2009 Timmy Yee
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * The Simulator class is the main class of the whole program. It
 * essentially simulates a computer or the kernel of an operating system.
 *
 * @author Timmy Yee
 * @author Keven Wong
 */
public final class Simulator
{
    /** The atomic time interval that the simulator clock ticks at. */
    public static final double TIME_UNIT = 0.1;

    private static double currentTime_ = 0;
    private static boolean paused_ = false;

    /**
     * A private constructor to prevent instantiating this static class.
     */
    private Simulator() {}

    /**
     * Gets the current time of the simulation run.
     *
     * @return The current time.
     */
    public static double getCurrentTime()
    {
        return currentTime_;
    }

    /**
     * Toggles pause mode on.
     */
    public static void pause()
    {
        paused_ = true;
    }

    /**
     * Toggles pause mode off.
     */
    public static void resume()
    {
        paused_ = false;
    }

    /**
     * Checks if the simulation is paused.
     *
     * @return True if paused, false otherwise.
     */
    public static boolean isPaused()
    {
        return paused_;
    }

    /**
     * Prints the header for the trace.
     */
    private static void printHeader()
    {
        Trace.append("---[ Operating System Simulation Trace ]---\n\n");
        Trace.append("Process Scheduling:\t\t%s\n",
                       Algorithm.valueOf(Scheduler.getProcessAlgorithm()));
        Trace.append("Memory Management:\t\t%s\n",
                       Algorithm.valueOf(Scheduler.getMemoryAlgorithm()));
        Trace.append("Time slice:\t\t\t%s msec\n", Processor.getTimeSlice());
        Trace.append("Context switching:\t\t%s msec\n",
                       Processor.getContextSwitch());
        Trace.append("Display queues every:\t\t%s msec\n\n",
                       Display.getDisplayInterval());
        Trace.append("Time\t\tEvent\n");
        Trace.append("(msec)\n");
        Trace.append("---\t\t------\n");
    }

    /**
     * Prints statistics at the end of the trace.
     */
    private static void printStatistics()
    {
        Trace.append("\n---[ Statistics ]---\n\n");
        Trace.append("Average turnaround time:\t%.1f msec\n",
                       Scheduler.getAverage(Time.TURNAROUND));
        Trace.append("Average waiting time:\t\t%.1f msec\n",
                       Scheduler.getAverage(Time.WAITING));
        Trace.append("Average response time:\t\t%.1f msec\n",
                       Scheduler.getAverage(Time.RESPONSE));
        Trace.append("Average page faults per second:\t%.6f faults\n",
                       Scheduler.getAverageFaultsPerSecond());
        Trace.append("CPU utilization:\t\t%.3f%%\n",
                       Scheduler.getUtilPercent());
    }

    /**
     * The main loop of the simulator.
     * <p>
     * This is where most of the computing of simulated processes is done.
     * All of this is done inside a worker thread so the GUI can update.
     * <p>
     * This function is called after the user loads in a file.
     */
    public static void mainLoop()
    {
        printHeader();

        currentTime_ = 0;
        while (Scheduler.areProcessesActive()) {
            if (isPaused())
                continue;

            Processor.handleInterrupts();
            Scheduler.checkForNewArrival();
            Scheduler.activate();

            double time = Scheduler.possiblySkipTime();
            if (time != 0)
                currentTime_ = time;
            else
                currentTime_ += TIME_UNIT;
        }

        printStatistics();
    }

    /**
     * Reads in test data for a simulation run.
     *
     * @param file The file containing test data.
     * @throws FileNotFoundException If the file name is phony.
     */
    public static void readTestData(File file) throws FileNotFoundException
    {
        Scanner test = new Scanner(file);

        Scheduler.initialize();
        Processor.reset();

        while (test.hasNextLine())
            try {
                Scheduler.add(new Process(test.nextLine().split("\\s+")));
            } catch (IllegalArgumentException e) {}

        test.close();
    }
}

